#! /bin/bash

# ===========================================================================
# File: "alphaed"
#                        Created: 2018-11-14 08:54:56
#              Last modification: 2019-02-12 07:19:04
# Author: Bernard Desgraupes
# e-mail: <bdesgraupes@users.sourceforge.net>
# Copyright (c) 2018-2019 Bernard Desgraupes
# All rights reserved.
# 
# Edit one or several files with Alpha.
# 
# Syntax:
#    alphaed file [file...]
# 
# ===========================================================================

VERSION_NUMBER="0.1"

ALPHA_APP=
ALPHA_ID=net.sourceforge.alphacocoa
CURR_DIR=`pwd`
result=0

# Source configuration file (if any). It may redefine ALPHA_APP.
AED_CONFIG_FILE=~/.alphaed.rc
if [ -e ${AED_CONFIG_FILE} ] ; then
	source ${AED_CONFIG_FILE}
fi

print_usage () {
	echoinfo "Usage: "
    echo "    " $(basename $0) "[options] file [file...]" 
    echo "    " $(basename $0) "[-h|-v]" 
    echoinfo "Options:"
    echo "    -a app    path of Alpha.app"
    echo "    -h        print usage"
    echo "    -v        print version"
	echo "Variable ALPHA_APP may be defined in configuration file '~/.alphaed.rc'."
    echoinfo "Examples:"
    echo "    $(basename $0) foo.tex"
    echo "    $(basename $0) foo.tex foo.bib"
    echo "    $(basename $0) foo.{tex,log}"
    echo "    $(basename $0) foo.*"
}

echoerror () {
	echo -e "\033[1;31m$1\033[0m"
}

echowarn () {
	echo -e "\033[1;33m$1\033[0m"
}

echoinfo () {
	echo -e "\033[1;36m$1\033[0m"
}


# Parse the command line options
while getopts ":a:hv" opt; do
	case $opt in
		a )
			ALPHA_APP=$OPTARG ;;
		h )
			echo $(basename $0) "- version $VERSION_NUMBER" 
			echo "Copyright (c) 2018-`date "+%Y"`, Bernard Desgraupes"
			echo "Edit files with Alpha."
			print_usage 
			exit 0 ;;
		v )
			echo $VERSION_NUMBER 
			exit 0 ;;
		\? )
			# pass on
			;;
	esac
done

# Skip the processed options
shift $((--OPTIND))

if [ $# == 0 ] ; then
	echoerror "Missing file name"
	echowarn "Type '$(basename $0) -h' for help"
	exit 1
fi

if [ "$ALPHA_APP" != "" ] ; then
	if ! [ -e $ALPHA_APP ] ; then
		>&2 echoerror "can't find $ALPHA_APP"
		exit 1
	fi	
fi

for f in "$@" ; do
	path=$f
	if ! [ -e "$path" ] ; then
		path="$CURR_DIR/$f"
	fi
	if [ -e "$path" ] ; then
		if [ "$ALPHA_APP" != "" ] ; then
			open -a "$ALPHA_APP" "$path"
		else
			open -b $ALPHA_ID "$path"
		fi
	else
		echowarn "can't find $f"
	fi
done

exit $result

